import { Component, OnInit } from '@angular/core';
import {TableUtil} from '../../../../util/table-util';
import {Path} from '../../../../portal/admin/admin-breadcrumb/breadcrumb';
import {OneDialogService} from '../../../../widgets/one-dialog/one-dialog.service';
import {MonitorService} from '../../../monitor/site-monitor/monitor.service';
import {Monitor} from '../../../monitor/site-monitor/monitor';
import {API, MsgConstants} from '../../../../constants/constants';
import {ActivatedRoute, Router} from '@angular/router';
import {ResponseUtil} from '../../../../util/response-util';
import {MsgResult} from '../../../../models/msg-result';
import {PageSubject} from '../../../../util/page-subject';
import {SitesService} from '../../../monitor/sites/sites.service';
import {SiteManageService} from '../site-manage.service';
import {SiteV2API} from '../../site-v2-constants';

@Component({
  selector: 'app-site-assign-dev',
  templateUrl: './site-assign-dev.component.html',
  styleUrls: ['./site-assign-dev.component.css']
})
export class SiteAssignDevComponent implements OnInit {

  monitor: Monitor;

  // 设备类型
  codMonitors;

  siteCode: string;

  siteName: string;

  isAllocat = '';
  snCode = '';
  monitorCode = '';

  table;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private tableUtil: TableUtil,
    private dialogService: OneDialogService,
    private responseUtil: ResponseUtil,
    private siteManageService: SiteManageService,
    private pageSubject: PageSubject
  ) {}

  ngOnInit() {
    this.pushPage();
    this.initData();
    this.loadSiteMonitor();
    this.getDeviceType();
  }

  /**
   *  生成面包屑
   */
  private pushPage() {
    const path = new Path('站点管理', null);
    this.pageSubject.pushPage('绑定设备', '查询', path);
  }
  initData() {
    this.siteCode =  this.route.snapshot.params['id'];
    this.siteName =  this.route.snapshot.params['siteName'];
  }
  /**
   * 搜索刷新
   */
  search() {
    this.table.bootstrapTable('refresh');
  }

  loadSiteMonitor() {
    this.table = this.tableUtil.load('one_table_assign-device', {
      columns: [
        {checkbox: true },
        {field: 'id', title: 'ID', align: 'left', visible: false, switchable: false},
        // {field: 'siteCode', title: '站点代码', align: 'left', visible: false, switchable: false},
        {field: 'siteName', title: '站点名称', align: 'left', class: 'one-table-col-2'},
        {field: 'snCode', title: '设备编号', align: 'left', class: 'one-table-col-2'},
        {field: 'monitorName', title: '设备类型', align: 'left', class: 'one-table-col-4'},
        {field: 'mPhone', title: '手机号', align: 'right', visible: false, class: 'one-table-col-2'},
        { field: 'ccid' , title: 'CCID', align: 'left' , class: 'one-table-col-2'},
        {field: 'receiveTimeMonitor', title: '数据接收时间', align: 'left', class: 'one-table-col-icon-6',
          sortName: 'RECEIVETIME', sortable: true, formatter: this.tableUtil.showToolTip},
        {field: 'receiveTimeStatus', title: '设备接收时间', align: 'left', class: 'one-table-col-icon-6',
          sortName: 'RECEIVETIME_DEV', sortable: true , formatter: this.tableUtil.showToolTip},
        {field: 'clientipinfClient', title: '客户端地址', align: 'left', class: 'one-table-col-2'},
        {field: 'clientipinfServer', title: '服务端地址', align: 'left', class: 'one-table-col-2', visible:  false},
        {field: 'clientipinfTranster', title: '下发通讯地址', align: 'left', class: 'one-table-col-2', visible: false},
        {field: 'statusUse', title: '使用状态', align: 'left', class: 'one-table-col-2', formatter: this.statusUseFormat},
        {field: 'statusWork', title: '运行状态', align: 'left', class: 'one-table-col-2', formatter: this.statusWorkFormat},
        // { field: 'remark',title:'说明' ,align:'left'},
        {field: 'transMode', title: '数据传输方式', align: 'left', class: 'one-table-col-6', formatter: this.yesOrNoFormat},
        {field: 'createDate', title: '创建日期', align: 'left', class: 'one-table-col-2',
          sortName: 'CREATE_DATE', sortable: true , visible: false},
        {field: 'updateDate', title: '修改日期', align: 'left', class: 'one-table-col-2',
          visible: false, sortName: 'UPDATE_DATE', sortable: true },
      ],
      idField: 'id',
      sidePagination: 'server',
      pagination: true,
      undefinedText: '-',
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 15, 50],
      paginationPreText: '上一页',
      paginationNextText: '下一页',
      paginationLoop: false, // 是否开启循环分页
      singleSelect: false, // 多选
      clickToSelect: true, // 点击选中
      toolbar: '#one_operation_assign-device',
      url: SiteV2API.siteDevicePageListV2,
      method: 'post',
      // 传递附加参数
      queryParams: (params) => {
        params.snCode = this.snCode;
        params.monitorCode = this.monitorCode;
        params.isAllocat = this.isAllocat;
        return params;
      },
      // 返回数据处理器
      responseHandler: (result) => {
        return this.responseUtil.bsPageHandler(result, () => {
          result.data.rows.forEach(function (value) {
            value.createDate = value.createDate || '';
            value.updateDate = value.updateDate || '';
            value.receiveTimeStatus = value.receiveTimeStatus || '-';
            value.receiveTimeMonitor = value.receiveTimeMonitor || '-';
          });
        });
      },
      height: 700, // table高度
      sortable: true,
      order: 'DESC',
      sortName: 'UPDATE_DATE',
      showColumns: true, // 显示自定义显示列按钮
      showRefresh: true, // 显示刷新按钮
      minimumCountColumns: 3, // 最少保留显示的列数量
      showToggle: true, // 显示视图切换按钮
      showPaginationSwitch: true, // 显示是否分页切换按钮
      // showExport: true,       // 是否显示导出按钮
      classes: 'table table-hover',
      striped: true, // 隔行变色
      mobileResponsive: true, // 响应式
      onLoadSuccess: (data) => {
        if (data.rows.length > 0) {
          data.rows.forEach((val, i ) => {
            if (this.siteCode === val.siteCode) {
              this.table.bootstrapTable('check', i);
            }
          })
        }
      }
    });
  }
  /**
   * 格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat = (value, row, index) => {
    if (value === '1') {
      return 'gprs';
    }
    if (value === '2') {
      return 'lora';
    }
    if (value === '3') {
      return 'nb';
    }
  };
  private statusWorkFormat = (value, row, index) => {
    if (value === '1') {
      return '正常';
    }
    if (value === '2') {
      return '故障';
    }
    if (value === '3') {
      return '停用';
    }
  };

  private statusUseFormat = (value, row, index) => {
    if (value === '0') {
      return '测试';
    }
    if (value === '1') {
      return '正式';
    }
  };

  /**
   * 取消保存
   */
  cancelSiteAssign() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }

  /**
   * 保存
   */
  saveAssignSite () {
    const rows = this.table.bootstrapTable('getSelections');
    if (rows.length <= 0) {
      return this.dialogService.modalInfo('请选择一条数据!');
    } else {
      const idsArr = this.tableUtil.getCloumns(rows, 'id');
      const sncodeArr = this.tableUtil.getCloumns(rows, 'snCode');
      this.dialogService.modalInfoWithCancelBtn('确定为设备编号为 ' + sncodeArr.join(' , ') + ' 分配给站点 - ' + this.siteName + '？', () => {
        this.requestSaveAssign(idsArr);
      });
    }
  }
  requestSaveAssign = (idsArr) => {
    this.siteManageService.postIdsForSite(this.siteCode, idsArr.join(',')).subscribe(
      result => this.responseUtil.success(result, this.processDeleteResult),
      error => this.responseUtil.error(error)
    )
  };
  /**
   * 处理保存结果
   * 1.判断是否保存成功；
   * @param result
   */
  private processDeleteResult = (result: MsgResult) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message);
      this.cancelSiteAssign();
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  /**
   * 获取设备类型
   */
  getDeviceType () {
    this.siteManageService.getDeviceType().subscribe(
      result => this.responseUtil.success(result, () => {
        this.codMonitors = result.data;
        console.log(result.data);
      }),
      error => this.responseUtil.error(error)
    )
  }
}
